﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 球员球队年度统计服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppPlayerTeamStatisticsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppPlayerTeamStatistics> _appPlayerTeamStatisticsRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public AppPlayerTeamStatisticsService(SqlSugarRepository<AppPlayerTeamStatistics> appPlayerTeamStatisticsRep, ISqlSugarClient sqlSugarClient)
    {
        _appPlayerTeamStatisticsRep = appPlayerTeamStatisticsRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询球员球队年度统计 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询球员球队年度统计")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppPlayerTeamStatisticsOutput>> Page(PageAppPlayerTeamStatisticsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appPlayerTeamStatisticsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.TeamId != null, u => u.TeamId == input.TeamId)
            .WhereIF(input.Goals != null, u => u.Goals == input.Goals)
            .WhereIF(input.Assists != null, u => u.Assists == input.Assists)
            .WhereIF(input.Attendances != null, u => u.Attendances == input.Attendances)
            .WhereIF(input.Points != null, u => u.Points == input.Points)
            .WhereIF(input.YellowCards != null, u => u.YellowCards == input.YellowCards)
            .WhereIF(input.RedCards != null, u => u.RedCards == input.RedCards)
            .WhereIF(input.MinutesPlayed != null, u => u.MinutesPlayed == input.MinutesPlayed)
            .WhereIF(input.Shots != null, u => u.Shots == input.Shots)
            .WhereIF(input.ShotsOnTarget != null, u => u.ShotsOnTarget == input.ShotsOnTarget)
            .WhereIF(input.Passes != null, u => u.Passes == input.Passes)
            .WhereIF(input.KeyPasses != null, u => u.KeyPasses == input.KeyPasses)
            .WhereIF(input.Tackles != null, u => u.Tackles == input.Tackles)
            .WhereIF(input.Interceptions != null, u => u.Interceptions == input.Interceptions)
            .WhereIF(input.Clearances != null, u => u.Clearances == input.Clearances)
            .WhereIF(input.Saves != null, u => u.Saves == input.Saves)
            .WhereIF(input.Fouls != null, u => u.Fouls == input.Fouls)
            .WhereIF(input.FoulsDrawn != null, u => u.FoulsDrawn == input.FoulsDrawn)
            .WhereIF(input.Offsides != null, u => u.Offsides == input.Offsides)
            .WhereIF(input.AerialDuelsWon != null, u => u.AerialDuelsWon == input.AerialDuelsWon)
            .WhereIF(input.Year != null, u => u.Year == input.Year)
            .LeftJoin<SysUser>((u, user) => u.UserId == user.Id)
            .LeftJoin<AppTeam>((u, user, team) => u.TeamId == team.Id)
            .Select((u, user, team) => new AppPlayerTeamStatisticsOutput
            {
                Id = u.Id,
                UserId = u.UserId,
                UserFkDisplayName = $"{user.RealName}",
                TeamId = u.TeamId,
                TeamFkDisplayName = $"{team.Name}",
                Year = u.Year,
                Goals = u.Goals,
                Assists = u.Assists,
                Attendances = u.Attendances,
                Points = u.Points,
                YellowCards = u.YellowCards,
                RedCards = u.RedCards,
                MinutesPlayed = u.MinutesPlayed,
                Shots = u.Shots,
                ShotsOnTarget = u.ShotsOnTarget,
                Passes = u.Passes,
                PassAccuracy = u.PassAccuracy,
                KeyPasses = u.KeyPasses,
                Tackles = u.Tackles,
                Interceptions = u.Interceptions,
                Clearances = u.Clearances,
                Saves = u.Saves,
                SaveAccuracy = u.SaveAccuracy,
                Fouls = u.Fouls,
                FoulsDrawn = u.FoulsDrawn,
                Offsides = u.Offsides,
                AerialDuelsWon = u.AerialDuelsWon,
                Rating = u.Rating,
                Remark = u.Remark,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取球员球队年度统计详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取球员球队年度统计详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppPlayerTeamStatistics> Detail([FromQuery] QueryByIdAppPlayerTeamStatisticsInput input)
    {
        return await _appPlayerTeamStatisticsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加球员球队年度统计 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加球员球队年度统计")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppPlayerTeamStatisticsInput input)
    {
        var entity = input.Adapt<AppPlayerTeamStatistics>();
        return await _appPlayerTeamStatisticsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新球员球队年度统计 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新球员球队年度统计")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppPlayerTeamStatisticsInput input)
    {
        var entity = input.Adapt<AppPlayerTeamStatistics>();
        await _appPlayerTeamStatisticsRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除球员球队年度统计 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除球员球队年度统计")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppPlayerTeamStatisticsInput input)
    {
        var entity = await _appPlayerTeamStatisticsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appPlayerTeamStatisticsRep.FakeDeleteAsync(entity);   //假删除
        //await _appPlayerTeamStatisticsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除球员球队年度统计 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除球员球队年度统计")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppPlayerTeamStatisticsInput> input)
    {
        var exp = Expressionable.Create<AppPlayerTeamStatistics>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appPlayerTeamStatisticsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appPlayerTeamStatisticsRep.FakeDeleteAsync(list);   //假删除
        //return await _appPlayerTeamStatisticsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppPlayerTeamStatisticsInput input)
    {
        var userIdData = await _appPlayerTeamStatisticsRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppPlayerTeamStatistics>(input.FromPage, (u, r) => u.Id == r.UserId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var teamIdData = await _appPlayerTeamStatisticsRep.Context.Queryable<AppTeam>()
            .InnerJoinIF<AppPlayerTeamStatistics>(input.FromPage, (u, r) => u.Id == r.TeamId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "userId", userIdData },
            { "teamId", teamIdData },
        };
    }
    
    /// <summary>
    /// 导出球员球队年度统计记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出球员球队年度统计记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppPlayerTeamStatisticsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppPlayerTeamStatisticsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "球员球队年度统计导出记录");
    }
    
    /// <summary>
    /// 下载球员球队年度统计数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载球员球队年度统计数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppPlayerTeamStatisticsOutput>(), "球员球队年度统计导入模板", (_, info) =>
        {
            if (nameof(ExportAppPlayerTeamStatisticsOutput.UserFkDisplayName) == info.Name) return _appPlayerTeamStatisticsRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppPlayerTeamStatisticsOutput.TeamFkDisplayName) == info.Name) return _appPlayerTeamStatisticsRep.Context.Queryable<AppTeam>().Select(u => $"{u.Name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入球员球队年度统计记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入球员球队年度统计记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppPlayerTeamStatisticsInput, AppPlayerTeamStatistics>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 球员Id
                    var userIdLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIdLabelList.Any()) {
                        var userIdLinkMap = _appPlayerTeamStatisticsRep.Context.Queryable<SysUser>().Where(u => userIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserId = userIdLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserId == null) e.Error = "球员Id链接失败";
                        });
                    }
                    // 链接 球队Id
                    var teamIdLabelList = pageItems.Where(x => x.TeamFkDisplayName != null).Select(x => x.TeamFkDisplayName).Distinct().ToList();
                    if (teamIdLabelList.Any()) {
                        var teamIdLinkMap = _appPlayerTeamStatisticsRep.Context.Queryable<AppTeam>().Where(u => teamIdLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TeamId = teamIdLinkMap.GetValueOrDefault(e.TeamFkDisplayName ?? "");
                            if (e.TeamId == null) e.Error = "球队Id链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.UserId == null){
                            x.Error = "球员Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TeamId == null){
                            x.Error = "球队Id不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppPlayerTeamStatistics>>();
                    
                    var storageable = _appPlayerTeamStatisticsRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Remark?.Length > 256, "备注长度不能超过256个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
